package packet1;

import java.util.HashSet;
import java.util.Set;

public class course {
    static Set<Integer> set = new HashSet<>();
    public static void main(String[] args) {
//        System.out.println(canFinish(5, new int[][]{{1,4},{2,4},{3,1},{3,2}}));
        System.out.println(canFinish(2, new int[][]{{1,0},{0,1}}));
    }
    public static boolean canFinish(int numCourses, int[][] prerequisites) {
        int isStudy[][] = new int[numCourses][2];
        for(int i = 0; i < prerequisites.length; i++)
        {
            isStudy[prerequisites[i][0]][0] = 1;
        }
        for(int i = 0; i < prerequisites.length; i++)
        {
            if(prerequisites[i][0] == prerequisites[i][1])
                return false;
            dfs(prerequisites[i][0], prerequisites, isStudy);
        }

        for (int i = 0; i < isStudy.length; i++) {
            if(isStudy[i][0] == 1)
                return false;
        }
        return true;
    }
    static void dfs(int num_of, int[][] pre, int[][] isStudy){
        for (int i = 0; i < pre.length; i++) {
            if(pre[i][0] == num_of)
            {
                if(isStudy[pre[i][1]][1] == 1 && !set.contains(pre[i][1]))
                    return;
                isStudy[pre[i][1]][1] = 1;
                if(isStudy[pre[i][1]][0] == 0)
                {
                    set.add(pre[i][1]);
                    isStudy[pre[i][0]][0] = 0;
                    set.add(pre[i][0]);
                    return;
                }
                dfs(pre[i][1], pre, isStudy);
            }
        }
        return;
    }

}
